<?php
namespace common\services\myhtsq;
use common\error\ErrorCode;
use common\services\BaseService;
use common\support\AuthHelper;
use common\support\Curl;
use Yii;
use yii\log\FileTarget;

/**
 * Created by PhpStorm.
 * User: xiazc01
 * Date: 2018/4/23
 * Time: 14:53
 */

class RentInterfaceService extends BaseService {

    /**
     * @param $contract_code
     * @return mixed
     * @throws \Exception
     */
    public static function getOrganizationInfo($contract_code){
        $timeStamp = time();
        $params = [
            'ts' => $timeStamp,
            'contract_code'=>$contract_code
        ];
        $target = \Yii::$app->params['RENT_INTERFACE_URL'];
        $secret = \Yii::$app->params["ext-api-secret"];
        $sign = AuthHelper::genSignWithSecret($params, $secret);
        $params['sign'] = $sign;
        $curl = new Curl();
        $content = $curl->post($target,$params);
        if (!YII_ENV_PROD){
            self::putLog($target,__METHOD__,true);
            self::putLog(var_export($params,true),__METHOD__,true);
            self::putLog($content,__METHOD__,true);
        }
        try{
            if($curl->getStatus() == 200){
                $data = json_decode($content,true);
                    if($data['retCode'] == ErrorCode::SUCCESS){
                    return $data['data'];
                }else{
                    throw new \Exception($data['errMsg']);
                }
            }
        }catch (\Exception $e){
            throw new \Exception('获取信息失败');
        }
    }

    public static function putLog($msg,$method,$res)
    {
        $time = microtime(true);
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/logs/rent_interface.log';

        $erroCode = empty($res)?1:0;

        $log->messages[] = [$msg,$erroCode,$method,$time];
        $log->export();
    }
}